from fastapi import APIRouter, HTTPException,Depends
from .services import ItemBrandService
from util.JWT import get_current_user
from .models import *
from datetime import datetime
import logging

# 配置基本日志
logging.basicConfig(level=logging.INFO)

router = APIRouter(prefix="/item-brand", tags=["物料签单管理"])

# 创建服务实例
service = ItemBrandService()

@router.get("/contracts", response_model=List[str])
async def get_contracts(id: dict = Depends(get_current_user)):
    """
    获取需要签单的合同列表
    
    Returns:
        合同号列表
    """
    try:
        contracts = service.get_contracts()
        return contracts
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取合同列表出错: {str(e)}")

@router.get("/picking-ids", response_model=List[str])
async def get_picking_ids(contract_no: str, id: dict = Depends(get_current_user)):
    """
    根据合同号获取识别码列表
    
    Args:
        contract_no: 合同号
        
    Returns:
        识别码列表
    """
    try:
        picking_ids = service.get_picking_ids(contract_no)
        return picking_ids
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取识别码列表出错: {str(e)}")

@router.get("/bill-data", response_model=BillDataResponse)
async def get_bill_data(picking_id: str, id: dict = Depends(get_current_user)):
    """
    查询签单相关数据
    
    Args:
        picking_id: 识别码
        
    Returns:
        签单数据，包括自制件和外购件清单、数量统计等
    """
    try:
        data = service.get_bill_data(picking_id)
        if "error" in data:
            raise HTTPException(status_code=400, detail=data["error"])
        return data
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询签单数据出错: {str(e)}")

@router.get("/brand-model", response_model=List[BrandModelItem])
async def get_brand_model(item: str, id: dict = Depends(get_current_user)):
    """
    查询品牌型号数据
    
    Args:
        item: 物料编码
        
    Returns:
        品牌型号信息列表
    """
    try:
        data = service.get_item_brand(item)
        if not data:
            raise HTTPException(status_code=404, detail=f"没有找到物料编码 {item} 的品牌型号信息")
        return data
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询品牌型号出错: {str(e)}")

@router.post("/submit", response_model=SubmitResponse)
async def submit_sign_data(data: SignDataRequest, id: dict = Depends(get_current_user)):
    """
    提交签单数据
    
    Args:
        data: 签单数据请求，包含合同号、识别码、物料品牌型号信息等
        
    Returns:
        提交结果
    """
    try:
        # 检查签单数据是否已存在
        if service.bool_sign_data(data.picking_id):
            return {"success": False, "message": "数据库中已有此识别码的签单数据，不能重复提交"}
        
        # 获取当前时间并格式化为SQL Server接受的格式
        current_time = datetime.now()
        formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
        
        # 计算还有多少份单没有签单(如果是最后一份单，返回值为1)
        remaining_forms = service.position_num(data.contract_no)
        
        # 判断是否需要拍照(如果需要拍照返回5，否则返回6)
        package_status = service.con_is_photo(data.contract_no)
        
        # 创建SQL语句列表，用于事务处理
        sql_statements = []
        
        # 处理无需签单的情况(特殊标记和无品牌型号数据)
        if hasattr(data, 'skip_validation') and data.skip_validation and not data.brand_models:
            # 无需签单的情况，直接更新识别码状态
            update_picking_sql = f"UPDATE Con_Picking SET SignTime='{formatted_time}', PackageQtyStatus=6 WHERE Con_PickingID='{data.picking_id}'"
            sql_statements.append(update_picking_sql)
            
            # 如果是最后一份单，更新合同状态
            if remaining_forms == 1:
                # 获取齐套时间
                qt_time = service.get_contract_date_time(data.contract_no, 2)
                
                # 计算签单周期(工作日)
                night_house = service.differ_date(qt_time, current_time, 1)
                qd_cycle = service.differ_date(qt_time, current_time, 2)
                
                update_contract_sql = f"UPDATE Contract SET QD_Time='{formatted_time}', QDCycle={qd_cycle}, QD_Cycle={night_house}, PackageQtyStatus={package_status}, CurrentException=0 WHERE ContractNO='{data.contract_no}'"
                sql_statements.append(update_contract_sql)
            
            # 重置变更状态
            # reset_change_sql = "UPDATE Change SET Step7=0"
            # sql_statements.append(reset_change_sql)
            
            # 执行SQL
            if service.execute_transaction(sql_statements):
                return {"success": True, "message": "提交成功"}
            else:
                return {"success": False, "message": "提交失败"}
        
        # 处理需要签单的情况
        if not data.brand_models:
            return {"success": False, "message": "没有添加任何品牌型号数据，无法提交"}
        
        # 对每个品牌型号进行插入操作
        for brand_model in data.brand_models:
            insert_sql = f"INSERT INTO SignData(Con_PickingID, ContractNO, Item, Brand, Model, Origin, PCS) VALUES('{data.picking_id}', '{data.contract_no}', '{brand_model.item}', '{brand_model.brand}', '{brand_model.model}', '{brand_model.origin}', {brand_model.quantity})"
            sql_statements.append(insert_sql)
        
        # 更新识别码状态
        update_picking_sql = f"UPDATE Con_Picking SET SignTime='{formatted_time}', PackageQtyStatus=6 WHERE Con_PickingID='{data.picking_id}'"
        sql_statements.append(update_picking_sql)
        
        # 如果是最后一份单，更新合同状态
        if remaining_forms == 1:
            # 获取齐套时间
            qt_time = service.get_contract_date_time(data.contract_no, 2)
            
            # 计算签单周期(工作日)
            night_house = service.differ_date(qt_time, current_time, 1)
            qd_cycle = service.differ_date(qt_time, current_time, 2)
            
            update_contract_sql = f"UPDATE Contract SET QD_Time='{formatted_time}', QDCycle={qd_cycle}, QD_Cycle={night_house}, PackageQtyStatus={package_status}, CurrentException=0 WHERE ContractNO='{data.contract_no}'"
            sql_statements.append(update_contract_sql)
            
            # 重置变更状态
            # reset_change_sql = "UPDATE Change SET Step7=0"
            # sql_statements.append(reset_change_sql)
        
        # 执行SQL
        if service.execute_transaction(sql_statements):
            return {"success": True, "message": "提交成功"}
        else:
            return {"success": False, "message": "提交失败"}
    except Exception as e:
        # 记录错误
        logging.error(f"提交签单数据出错: {str(e)}")
        return {"success": False, "message": f"提交签单数据出错: {str(e)}"}

@router.get("/check-sign-data/{picking_id}", response_model=dict)
async def check_sign_data_exists(picking_id: str):
    """
    检查指定识别码的签单数据是否已存在
    
    Args:
        picking_id: 识别码
        
    Returns:
        存在标识和消息
    """
    try:
        exists = service.bool_sign_data(picking_id)
        return {"exists": exists, "message": "查询成功"}
    except Exception as e:
        logging.error(f"检查签单数据失败: {str(e)}")
        return {"exists": False, "message": f"检查签单数据失败: {str(e)}"}

@router.get("/photo-required-items")
async def get_photo_required_items(contract_no: str):
    """获取需要拍照的物料列表"""
    result = service.get_photo_required_items(contract_no)
    if result["code"] != 200:
        raise HTTPException(status_code=result["code"], detail=result["message"])
    return result
